package com.smart.manager.finance.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.smart.common.entities.core.Page;
import com.smart.manager.finance.entities.bodys.RAccountWxpay;
import com.smart.manager.finance.entities.models.FinanceAccountWxpay;
import com.smart.manager.finance.entities.models.query.QFinanceAccountWxpay;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付中心-订单管理
 *
 * @author Administrator
 */

@Log4j2
@Service
@RequiredArgsConstructor
public class AccountWxpayRepository {
    private final WxPayService wxPayService;


    public Page<FinanceAccountWxpay> pageList(RAccountWxpay.SearchBody search) {
        QFinanceAccountWxpay query = new QFinanceAccountWxpay();
        Opt.ofBlankAble(search.getMchId()).ifPresent(x -> query.mchId.contains(x));
        Opt.ofBlankAble(search.getMchName()).ifPresent(x -> query.mchName.contains(x));
        Opt.ofBlankAble(search.getAppId()).ifPresent(x -> query.appId.contains(x));
        Opt.ofNullable(search.getAppType()).ifPresent(x -> query.appType.eq(x));
        Opt.ofBlankAble(search.getDescription()).ifPresent(x -> query.description.contains(x));
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows()).order().id.desc();
        Page<FinanceAccountWxpay> load = new Page<FinanceAccountWxpay>().load(query.findPagedList());
        load.getRecords().forEach(x -> {
            x.setPrivateKey(Base64.decodeStr(x.getPrivateKey()));
            x.setPrivateCert(Base64.decodeStr(x.getPrivateCert()));
        });
        return new Page<FinanceAccountWxpay>().load(query.findPagedList());
    }

    /**
     * 添加
     *
     * @param form 形式
     */
    public void add(RAccountWxpay.EditBody form) {
        FinanceAccountWxpay record = new QFinanceAccountWxpay().appId.eq(form.getAppId()).findOne();
        Assert.isNull(record, "应用ID已存在");
        //加密
        String privateCert = Base64.encode(form.getPrivateCert());
        String key = Base64.encode(form.getPrivateKey());

        FinanceAccountWxpay paymentWechat = BeanUtil.copyProperties(form, FinanceAccountWxpay.class);
        paymentWechat.setPrivateCert(privateCert);
        paymentWechat.setPrivateKey(key);
        paymentWechat.save();
        updateWechatPayConfig();
    }

    /**
     * 更新
     *
     * @param id   id
     * @param form 形式
     */
    public void update(Long id, RAccountWxpay.EditBody form) {
        FinanceAccountWxpay record = new QFinanceAccountWxpay().id.eq(id).findOne();
        Assert.notNull(record, "微信支付账户配置不存在");
        BeanUtil.copyProperties(form, record);
        String privateCert = Base64.encode(form.getPrivateCert());
        String key = Base64.encode(form.getPrivateKey());
        record.setPrivateCert(privateCert);
        record.setPrivateKey(key);
        record.update();
        updateWechatPayConfig();

    }

    /**
     * 批量删除
     *
     * @param idList id列表
     * @return int
     */
    public int delByIds(List<Long> idList) {
        int i = DB.deleteAll(FinanceAccountWxpay.class, idList);
        updateWechatPayConfig();
        return i;

    }


    /**
     * 获取所有支付配置列表
     *
     * @return {@link List}<{@link FinanceAccountWxpay}>
     */
    public List<FinanceAccountWxpay> list() {
        return new QFinanceAccountWxpay().findList();
    }


    /**
     * 更新微信支付配置信息
     */
    public void updateWechatPayConfig() {
        log.warn("正在更新微信支付配置信息.....");
        Map<String, WxPayConfig> result = new HashMap<>(0);
        List<FinanceAccountWxpay> list = new QFinanceAccountWxpay().findList();
        if (CollectionUtil.isEmpty(list)) {
            result.put("DEFAULT", null);
        } else {
            for (FinanceAccountWxpay paymentWechat : list) {
                WxPayConfig payConfig = new WxPayConfig();
                payConfig.setAppId(paymentWechat.getAppId());
                payConfig.setMchId(paymentWechat.getMchId());
                payConfig.setApiV3Key(paymentWechat.getV3Key());
                //设置证书
                if (StrUtil.isNotBlank(paymentWechat.getPrivateCert())) {
                    payConfig.setPrivateCertContent(Base64.decode(paymentWechat.getPrivateCert()));
                }
                //设置秘钥
                if (StrUtil.isNotBlank(paymentWechat.getPrivateKey())) {
                    payConfig.setPrivateKeyContent(Base64.decode(paymentWechat.getPrivateKey()));
                }
                result.put(paymentWechat.getAppId(), payConfig);
            }
        }
        wxPayService.setMultiConfig(result);
    }

    public FinanceAccountWxpay getAccountWxpay(  String appId) {
        FinanceAccountWxpay accountWxpay = new QFinanceAccountWxpay().appId.eq(appId).setMaxRows(1).findOne();
        Assert.notNull(accountWxpay , "微信支付收款应用ID查询失败");
        return accountWxpay;
    }
}
